using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Configuration;
using Metro.Admin.BusinessEntities;
using Microsoft.Practices.SmartClient.DisconnectedAgent;
using Metro.SmartClient.Infrastructure.Library.Properties;
using Metro.SmartClient.Infrastructure.Library;
using Microsoft.Practices.CompositeUI;
using Microsoft.Practices.CompositeUI.Services;
using Microsoft.Practices.ObjectBuilder;
using Metro.SmartClient.Infrastructure.Interface;

using Metro.SmartClient.Infrastructure.Interface.SharedService;

namespace Metro.SmartClient.Infrastructure.Library.Services
{
	public class Login : Form
	{
        public delegate void UIDelegate();
		private Label lblLogin;
		private Button btnCancel;
		private Button btnOk;
		private Label lblText;
		private IContainer components = null;
		private TextBox txtLogin;
		private TextBox txtPassword;
        private Label lblPassword;
        private PictureBox pbxLogo;
        private LinkLabel lblProxy;
        private CheckBox chkRemember;
        private Metro.Admin.BusinessEntities.User loginUser = null;
        private Metro.SmartClient.Infrastructure.Interface.DSA.SharedServiceClient.Agent sharedServiceAgent;
        private IConnectionMonitor connectionMonitor;
        private IRequestQueue requestQueue;
        private WorkItem localWorkitem;
        //private SharedServiceClient client;

        public Login([ServiceDependency] WorkItem workItem)
		{
			InitializeComponent();
            Metro.SmartClient.Infrastructure.Interface.DSA.SharedServiceClient.Callback.GetUsersAuthenticationReturn += new EventHandler<EventArgs<Metro.Admin.BusinessEntities.User>>(this.GetUsersAuthenticationReturn);
            Metro.SmartClient.Infrastructure.Interface.DSA.SharedServiceClient.Callback.GetUsersAuthenticationException += new EventHandler<EventArgs<Exception>>(this.GetUsersAuthenticationException);
            this.localWorkitem = workItem;  
       	}

        public Metro.Admin.BusinessEntities.User SelectUser()
		{
			if (DialogResult.OK == ShowDialog())
			{
                return loginUser;
			}

			return null;
		}

        [ServiceDependency]
        public WorkItem WorkItem
        {
            get { return localWorkitem; }
            set { localWorkitem = value; }
        }

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && (components != null))
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Login));
            this.lblLogin = new System.Windows.Forms.Label();
            this.btnCancel = new System.Windows.Forms.Button();
            this.btnOk = new System.Windows.Forms.Button();
            this.lblText = new System.Windows.Forms.Label();
            this.txtLogin = new System.Windows.Forms.TextBox();
            this.txtPassword = new System.Windows.Forms.TextBox();
            this.lblPassword = new System.Windows.Forms.Label();
            this.pbxLogo = new System.Windows.Forms.PictureBox();
            this.lblProxy = new System.Windows.Forms.LinkLabel();
            this.chkRemember = new System.Windows.Forms.CheckBox();
            ((System.ComponentModel.ISupportInitialize)(this.pbxLogo)).BeginInit();
            this.SuspendLayout();
            // 
            // lblLogin
            // 
            resources.ApplyResources(this.lblLogin, "lblLogin");
            this.lblLogin.Name = "lblLogin";
            // 
            // btnCancel
            // 
            this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            resources.ApplyResources(this.btnCancel, "btnCancel");
            this.btnCancel.Name = "btnCancel";
            this.btnCancel.UseVisualStyleBackColor = true;
            // 
            // btnOk
            // 
            resources.ApplyResources(this.btnOk, "btnOk");
            this.btnOk.Name = "btnOk";
            this.btnOk.UseVisualStyleBackColor = true;
            this.btnOk.Click += new System.EventHandler(this.btnOk_Click);
            // 
            // lblText
            // 
            resources.ApplyResources(this.lblText, "lblText");
            this.lblText.ForeColor = System.Drawing.SystemColors.HotTrack;
            this.lblText.Name = "lblText";
            // 
            // txtLogin
            // 
            resources.ApplyResources(this.txtLogin, "txtLogin");
            this.txtLogin.Name = "txtLogin";
            // 
            // txtPassword
            // 
            resources.ApplyResources(this.txtPassword, "txtPassword");
            this.txtPassword.Name = "txtPassword";
            // 
            // lblPassword
            // 
            resources.ApplyResources(this.lblPassword, "lblPassword");
            this.lblPassword.Name = "lblPassword";
            // 
            // pbxLogo
            // 
            resources.ApplyResources(this.pbxLogo, "pbxLogo");
            this.pbxLogo.Name = "pbxLogo";
            this.pbxLogo.TabStop = false;
            // 
            // lblProxy
            // 
            resources.ApplyResources(this.lblProxy, "lblProxy");
            this.lblProxy.Name = "lblProxy";
            this.lblProxy.TabStop = true;
            // 
            // chkRemember
            // 
            resources.ApplyResources(this.chkRemember, "chkRemember");
            this.chkRemember.Name = "chkRemember";
            this.chkRemember.UseVisualStyleBackColor = true;
            // 
            // Login
            // 
            this.AcceptButton = this.btnOk;
            resources.ApplyResources(this, "$this");
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.CancelButton = this.btnCancel;
            this.CausesValidation = false;
            this.Controls.Add(this.chkRemember);
            this.Controls.Add(this.lblProxy);
            this.Controls.Add(this.pbxLogo);
            this.Controls.Add(this.lblPassword);
            this.Controls.Add(this.txtPassword);
            this.Controls.Add(this.txtLogin);
            this.Controls.Add(this.lblText);
            this.Controls.Add(this.btnOk);
            this.Controls.Add(this.btnCancel);
            this.Controls.Add(this.lblLogin);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "Login";
            this.TopMost = true;
            this.Load += new System.EventHandler(this.Login_Load);
            ((System.ComponentModel.ISupportInitialize)(this.pbxLogo)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

		}

		#endregion

		private void btnOk_Click(object sender, EventArgs e)
		{
            try
            {
                sharedServiceAgent = new Metro.SmartClient.Infrastructure.Interface.DSA.SharedServiceClient.Agent(requestQueue);
                //client = new SharedServiceClient(); 
                 
                string login = txtLogin.Text.Trim();
                string pass = txtPassword.Text.Trim();

                //loginUser =  client.UsersAuthentication(login, pass);  

                sharedServiceAgent.UsersAuthentication(login, pass);
                
                //if (loginUser != null)
                //{
                //    this.DialogResult = DialogResult.OK;
                //    this.Close();
                //}
                //else
                //{
                //    MessageBox.Show(Properties.Resources.UserNotFoundMessage, "btnOk_Click");
                //}


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "btnOk_Click");  
            }
		}


        private void GetUsersAuthenticationReturn(object sender, EventArgs<Metro.Admin.BusinessEntities.User> e)
        {
            UIDelegate uiDelegate = new UIDelegate(this.UIDelegateMain); 
            try
            {
                loginUser = e.Data;
                if (loginUser != null)
                {
                    if (this.InvokeRequired)
                    {
                        this.Invoke(uiDelegate);
                    }
                }
                else
                {
                    MessageBox.Show(Properties.Resources.UserNotFoundMessage, "btnOk_Click");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "GetUsersAuthenticationReturn");
            }
            
        }

        private void GetUsersAuthenticationException(object sender, EventArgs<Exception> e)
        {
            if (Connected)
            {
                MessageBox.Show(Properties.Resources.ErrorRetrievingUser + " " + e.Data.Message, "GetUsersAuthenticationException");
            }
            else
            {
                MessageBox.Show(Properties.Resources.OfflineMessage + " " + e.Data.Message, "GetUsersAuthenticationException");
            }
        }

        private void Login_Load(object sender, EventArgs e)
        {
            try
            {
                pbxLogo.Image = Resources.logo;
                this.Icon = Resources.coin;

                connectionMonitor = WorkItem.RootWorkItem.Services.Get<IConnectionMonitor>();
                requestQueue = WorkItem.RootWorkItem.Services.Get<IRequestQueue>();
                                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Login_Load");  
            }
        }

        private bool Connected
        {
            get { return this.connectionMonitor.IsConnected; }
        }

        public void UIDelegateMain()
        {
            try
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "UIDelegateMain");  
            }
        }
       
	}
}
